package handler

import (
	"effect-mgr/cache"
	"effect-mgr/model"
	"effect-mgr/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": "400",
			"msg":  "不能为空",
		})
		return
	}
	var user model.User
	model.DB.Where("username =?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": "400",
			"msg":  "该用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": "400",
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": "400",
		"msg":  "ok",
		"user": user,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": "400",
			"msg":  "不能为空",
		})
		return
	}
	data := model.Article{
		Title:   title,
		Content: content,
	}
	model.DB.Create(&data)
	var art model.Article
	rediskey := "redis_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id =?", data.ID).Find(&art)
	jsondata, _ := json.Marshal(art)
	cache.Rdb.Set(cache.Ctx, rediskey, jsondata, time.Hour*2)
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.PostForm("id")
	var art model.Article
	err := model.DB.Where("id=?", id).Find(&art).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": "200",
			"msg":  "该用户不存在",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "fb",
		"data": art,
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	model.DB.Where("id =?", id).Delete(&model.Article{})
	rediskey := "redis_" + id
	cache.Rdb.Del(cache.Ctx, rediskey)
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var art []model.Article
	rediskey := "redis_list"
	cachedata, _ := cache.Rdb.Get(cache.Ctx, rediskey).Result()
	if cachedata == "" {
		model.DB.Find(&art)
		jsondata, _ := json.Marshal(art)
		cache.Rdb.Set(cache.Ctx, rediskey, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachedata), &art)
	}
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "展示成功",
		"data": art,
	})
	return
}
